package com.yuye.excel.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.util.StringUtil;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StringUtils;

public class EasyExcelUtils {

	public static <T> void webWriteExcel(HttpServletResponse response, String filePath , List<T> excelErrDtos, Class<? extends BaseRowModel> class1,
			String sheetsTitle, List<List<String>> headList) {
		ExcelWriter writer = null;
		OutputStream outputStream = null;
		try {
			if(StringUtils.isEmpty(filePath)) {
				outputStream = response.getOutputStream();
			}else {
				outputStream = new FileOutputStream(filePath);
			}
			
			
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {

			writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true);

			Sheet sheet = new Sheet(1, 0, class1);
			sheet.setSheetName(sheetsTitle);

			if (headList != null || headList.size() <= 0) {
				sheet.setHead(headList);
			}

			writer.write(excelErrDtos, sheet);
			writer.finish();
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(StringUtils.isEmpty(filePath)) {
					response.getOutputStream().close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	public static String getExcelErrorMsgByForamt(Integer rowIndex, Integer index, String msgFormat) {
		msgFormat = String.format(msgFormat, rowIndex + 1, index + 1);
		return msgFormat;
	}
	
	
	public static String getExcelErrorMsgByForamt(String sheetName,Integer rowIndex,  Integer index, String msgFormat) {
		msgFormat = String.format(msgFormat, sheetName, rowIndex + 1, index + 1);
		return msgFormat;
	}

}
